#include <Arduino.h>
#include <oled.h>
#include <Versatile_RotaryEncoder.h>

int lineNr = 0;

// There are 2 different versions of the board
// OLED display=OLED(2,14,4);
OLED display = OLED(18, 17, NO_RESET_PIN, OLED::W_128, OLED::H_64);
Versatile_RotaryEncoder versatile_encoder = Versatile_RotaryEncoder(21, 23, 22);

void handleRotate(int8_t rotation)
{
    Serial.print("#1 Rotated: ");
    if (rotation > 0)
        Serial.println("Right");
    else
        Serial.println("Left");
}

void handlePress()
{
    Serial.println("#4 Pressed");
}

void setup()
{
    //串口
    Serial.begin(115200);
    // PWM
    ledcSetup(0, 20000, 10);
    ledcAttachPin(27, 0);
    //编码器
    versatile_encoder.setHandleRotate(handleRotate);
    versatile_encoder.setHandlePress(handlePress);
    //显示屏
    display.begin();
    display.setTTYMode(true);
    display.printf("TTY:>Press button");
    // LED
    pinMode(GPIO_NUM_2, OUTPUT);
    Serial.print("OK");
}

void loop()
{
    // // Draw solid circles
    // digitalWrite(GPIO_NUM_2, HIGH);
    // delay(500);
    // display.draw_circle(36, 16, 14, OLED::SOLID);
    // display.display();
    // digitalWrite(GPIO_NUM_2, LOW);
    // delay(500);
    // display.draw_circle(36, 16, 7, OLED::SOLID, OLED::BLACK);
    // display.display();
    // display.clear();

    ledcWrite(0, 200); //指定通道输出一定占空比波形

    if (versatile_encoder.ReadEncoder())
    {
        // Do something here whenever an encoder action is read
    }

    if (digitalRead(0) == LOW)
    {
        lineNr++;

        /**
         * First Method: same as Serial.print()
         * 3 lines
         * display.print('\n');
         * display.print("TTY:>Button press ");
         * display.print(lineNr);
         */

        /**
         * Second Method: use printf()
         * ...only une line
         */
        display.printf("\nTTY:>Button press %d", lineNr);

        if (lineNr == 65535)
            lineNr = 0;
        delay(200);
    }
}
